package com.ep.thirdPlatformProject.oa.util;

import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import com.ep.thirdPlatformProject.system.config.oa.WorkflowFormProperties;
import com.ep.thirdPlatformProject.oa.enums.WorkflowEnum;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import weaver.workflow.webservices.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * OA 实体类工具
 *
 * @author Karl
 * @date 2024/05/28
 */
@Component
public class OACommonEntityUtil {

    @Resource
    private WorkflowFormProperties properties;


    public static final ObjectMapper objMapper = new ObjectMapper();

    /**
     * 构建工作流请求信息对象。
     *
     * @return 构建好的WorkflowRequestInfo对象。
     */
    public  WorkflowRequestInfo buildWorkflowRequestInfo(WorkflowEnum workflowEnum,
                                                               Map<String, Object> mainTableMap, Integer creatorId) {
        return buildWorkflowRequestInfo(workflowEnum,creatorId, mainTableMap, new ArrayList<>());
    }

    /**
     * 构建工作流请求信息对象。
     *
     * @return 构建好的WorkflowRequestInfo对象。
     */
    public  WorkflowRequestInfo buildWorkflowRequestInfo(WorkflowEnum workflowEnum,Integer creatorId,
                                                               Map<String, Object> mainTableMap, List<Map<String, Object>> detailTableList) {

        WorkflowRequestInfo requestInfo = new WorkflowRequestInfo();
        // 初始化工作流基础信息
        WorkflowBaseInfo workflowBaseInfo = new WorkflowBaseInfo();
        // 设置请求可查看
        requestInfo.setCanView(true);
        // 设置请求可编辑
        requestInfo.setCanEdit(true);
        // 设置请求标题
        requestInfo.setRequestName(workflowEnum.getTitle());
        // 设置请求重要级别
        requestInfo.setRequestLevel(workflowEnum.getLevel());
        // 设置创建者ID
        requestInfo.setCreatorId(String.valueOf(creatorId));

        List<Map<String, Integer>> workFlowIdList = properties.getWorkFlowIdList();
        for (Map<String, Integer> map : workFlowIdList) {
            if (map.containsKey(workflowEnum.getWorkflowId())){
                // 设置流程ID
                workflowBaseInfo.setWorkflowId(String.valueOf(map.get(workflowEnum.getWorkflowId())));
            }
        }

        // 设置流程名称
        workflowBaseInfo.setWorkflowName(workflowEnum.getFlowName());
        // 设置流程类型名称
        workflowBaseInfo.setWorkflowTypeName(workflowEnum.getFlowName());

        // 设置工作流基础信息到请求信息中
        requestInfo.setWorkflowBaseInfo(workflowBaseInfo);

        // 设置主表信息
        WorkflowMainTableInfo mainTableInfo = buildWorkflowRequestMainTable(mainTableMap);
        requestInfo.setWorkflowMainTableInfo(mainTableInfo);

        // 设置明细表信息
        WorkflowDetailTableInfo[] detailTableInfo = buildWorkflowDetailTableInfos(detailTableList);
        requestInfo.setWorkflowDetailTableInfos(detailTableInfo);

        return requestInfo;
    }


    /**
     * 构建工作流请求主表信息。该方法通过遍历给定的map，将map中的键值对转换为工作流请求表的字段记录。
     *
     * @param map 包含工作流请求数据的map，其中键代表字段名，值代表字段值。
     * @return WorkflowMainTableInfo 工作流主表信息对象，包含了从map转换得到的字段记录。
     */
    private static WorkflowMainTableInfo buildWorkflowRequestMainTable(Map<String, Object> map) {
        WorkflowMainTableInfo workflowMainTableInfo = new WorkflowMainTableInfo();

        if (map == null || map.isEmpty()) {
            return workflowMainTableInfo;
        }
        // 构建参数
        WorkflowRequestTableRecord[] workflowRequestTableRecord = buildWorkflowRequestTableRecords(map);

        // 设置主表记录到工作流主表信息对象中
        workflowMainTableInfo.setRequestRecords(workflowRequestTableRecord);
        return workflowMainTableInfo;
    }


    /**
     * 构建工作流详细表信息（暂时只能使用一条）
     *
     * @param detailTableList list
     * @return {@link WorkflowDetailTableInfo[] }
     */
    private static WorkflowDetailTableInfo[] buildWorkflowDetailTableInfos(List<Map<String, Object>> detailTableList) {
        if (detailTableList == null || detailTableList.isEmpty()) {
            return new WorkflowDetailTableInfo[0];
        }
        WorkflowDetailTableInfo[] detailTableInfo = new WorkflowDetailTableInfo[1];
        detailTableInfo[0] = new WorkflowDetailTableInfo();
        WorkflowRequestTableRecord[] workflowRequestTableRecords = new WorkflowRequestTableRecord[detailTableList.size()];
        for (int i = 0; i < detailTableList.size(); i++) {
            Map<String, Object> map = detailTableList.get(i);
            // 构建参数
            workflowRequestTableRecords[i] = buildWorkflowRequestTableRecords(map)[0];

        }
        // 设置明细表的记录
        detailTableInfo[0].setWorkflowRequestTableRecords(workflowRequestTableRecords);
        return detailTableInfo;
    }


    /**
     * 构建工作流请求表记录
     *
     * @param map 集合
     * @return {@link WorkflowRequestTableRecord[] }
     */
    public static WorkflowRequestTableRecord[] buildWorkflowRequestTableRecords(Map<String, Object> map) {
        WorkflowRequestTableRecord[] workflowRequestTableRecord = new WorkflowRequestTableRecord[1];
        // 初始化字段记录列表
        List<WorkflowRequestTableField> list = new ArrayList<>();
        // 遍历map，将每个键值对转换为字段记录并添加到列表中
        for (String key : map.keySet()) {
            WorkflowRequestTableField field = new WorkflowRequestTableField();
            field.setEdit(true);
            field.setView(true);
            field.setFieldName(key);
            field.setFieldValue(Opt.ofNullable(map.getOrDefault(key, "")).orElse("").toString());
            list.add(field);
        }
        // 将字段记录列表转换为数组，设置到主表记录中
        WorkflowRequestTableField[] fields = list.toArray(new WorkflowRequestTableField[]{});
        workflowRequestTableRecord[0] = new WorkflowRequestTableRecord();
        workflowRequestTableRecord[0].setWorkflowRequestTableFields(fields);

        return workflowRequestTableRecord;
    }

    /**
     * 构建实体到参数映射
     *
     * @param entity 实体
     * @return {@link Map }<{@link String }, {@link Object }>
     */
    public static Map<String, Object> buildEntityToParamMap(Object entity) {
        try {

            String str = objMapper.writeValueAsString(entity);
            return objMapper.readValue(str, new TypeReference<Map<String, Object>>() {
            });
        } catch (Exception e) {

            throw new RuntimeException("参数实体转化为map失败：" + e.getMessage(), e);
        }

    }

}
